import type { Recordable } from '@vben/types';

import { ref } from 'vue';

import { useAppConfig } from '@vben/hooks';

import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { doLogin, postDoLogin } from '#/api/admin/appstore';

export const useAppstoreStore = defineStore('appstore', () => {
  const loginLoading = ref(false);

  const showLoginModel = ref(false);
  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function appStoreLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
    let access_token = '';
    try {
      loginLoading.value = true;
      const { code, data } = await doLogin(params);
      if (code) {
        access_token = data.access_toke;
        const isRefreshAccessToken = false;
        if (isRefreshAccessToken) {
          const domain = baseURL ?? window.location.host;
          const { msg } = await postDoLogin({
            access_token: data.access_token,
            domain,
          });
          message.success(msg);
        }

        const { msg } = await postDoLogin({
          access_token: data.access_token,
        });
        message.success(msg);
        await onSuccess?.();
      } else {
        message.error('登录失败');
      }
    } finally {
      loginLoading.value = false;
      showLoginModel.value = false;
    }

    return {
      access_token,
    };
  }

  function $reset() {
    loginLoading.value = false;
    showLoginModel.value = false;
  }

  return {
    $reset,
    appStoreLogin,
    loginLoading,
    showLoginModel,
  };
});
